#include "FileIdHandler.h"

#ifndef ZERO
	#define ZERO 0
#endif

#ifndef UNO
	#define UNO 1
#endif

//-------------------------------------------------------------------------
//	IMPLEMENTATION OF CLASS FileIdHandler
//-------------------------------------------------------------------------



FileIdHandler* FileIdHandler::GetInstance()
{
	static FileIdHandler instance;
	
	return &instance;
}

FileIdHandler::FileIdHandler()
	: lista(NULL),
	max(UNO)
{
	lista = new List();
}

FileIdHandler::~FileIdHandler()
{
	if(lista != NULL)
		delete lista;
	lista = NULL;
}

int FileIdHandler::getHandler(char *filename)
{
	int toReturn = RES_ERROR;
	IdHandler* data = new IdHandler();
	data->setFilename(filename);
	if(lista->get((Data*)data))
	{
		toReturn = data->getIdHandler();
	}
	delete data;
	return toReturn;
}

void FileIdHandler::addHandler(char *filename)
{
	IdHandler* data = new IdHandler();
	data->setFilename(filename);
	data->setIdHandler(max);

	if(!lista->get((Data*)data))
	{
		lista->add((Data*)data);
		max++;
	}
	delete data;
}

//-------------------------------------------------------------------------
//	IMPLEMENTATION OF CLASS IdHandler
//-------------------------------------------------------------------------

IdHandler::IdHandler()
	: filename(NULL),
	handler(ZERO)
{
}

IdHandler::~IdHandler()
{
	if(filename != NULL)
		delete []filename;
	handler = ZERO;
}

void IdHandler::getFilename(char* name)
{
	if(name != NULL && filename != NULL)
		memcpy(name, filename, strlen(filename));
}

void IdHandler::setFilename(char* name)
{
	unsigned int size = ZERO;

	if(name != NULL)
	{
		size = strlen(name) + UNO;
		if(filename != NULL)
			delete []filename;
		filename = new char[size];
		memcpy(filename, name, size);
	}
}

void IdHandler::setIdHandler(int h)
{
	handler = h;
}

int IdHandler::getIdHandler()
{
	return handler;
}

bool IdHandler::equal(Data* data)
{
	if(data != NULL)
		if(filename != NULL && ((IdHandler*)data)->filename != NULL)
			return (memcmp(filename, ((IdHandler*)data)->filename, strlen(filename)) == ZERO);
	return false;
}

void IdHandler::copy(Data** data)
{
	if(data != NULL && (*data) != NULL)
	{
		((IdHandler*)(*data))->setFilename(this->filename);
		((IdHandler*)(*data))->setIdHandler(this->handler);
	}
}

Data* IdHandler::allocate()
{
	Data* data = new IdHandler();
	this->copy(&data);
	return data;
}

void IdHandler::print()
{
	std::cout << "FILENAME: " << filename << std::endl;
	std::cout << "HANDLER: " << handler << std::endl;
}

 
